<!--
 * @Description: 
 * @Author: william
 * @Date: 2025-07-02 13:53:59
 * @LastEditors: william
 * @LastEditTime: 2025-10-14 16:18:09
-->
<template>
  <nw-PageTitle :title="props.type === 'add' ? '新增菜谱' : '菜谱明细'" isBack>
    <template #right>
      <uni-icons
        v-if="props.type !== 'add'"
        type="trash"
        :size="iconSize"
        color="#333"
        @click="handleDelete"
      />
    </template>
  </nw-PageTitle>
  <nw-PageContainer>
    <scroll-view class="scroll-content" scroll-y>
      <view class="recipe-content">
        <view class="recipe-concise">
          <view class="rc-left" @click="handleModifyPicture">
            <image
              :src="formData.base64Image || formData.picturePath"
              mode="aspectFit"
              class="recipe-img"
            />
          </view>
          <view class="rc-content">
            <view class="rcc-top">
              <view class="rcct-left">
                <view class="rcc-label">菜谱名称</view>
                <nw-Input
                  v-model="formData.name"
                  label="菜谱名称"
                  style="max-width: 200rpx"
                ></nw-Input>
              </view>
              <view class="rcct-right">
                <nw-Button
                  text="立即烹饪"
                  :disabled="props.type === 'add' || props.recipeType === '1'"
                  @click="handleCookImmedi"
                ></nw-Button>
              </view>
            </view>
            <view class="rcc-items">
              <view class="rcc-item">
                <view class="rcc-label">口味：</view>
                <view class="uss-form-select">
                  <zxz-uni-data-select
                    v-model="formData.tasteStyle"
                    :localdata="recipeTasteOptions"
                    placeholder="选择"
                    :emptyTips="$t('system.noOption')"
                    :clear="false"
                    dataKey="label"
                    @change="handleRoleChange"
                  ></zxz-uni-data-select>
                </view>
              </view>
              <view class="rcc-item">
                <view class="rcc-label">菜系：</view>
                <view class="uss-form-select">
                  <zxz-uni-data-select
                    v-model="formData.cookStyle"
                    :localdata="recipeCookStyleOptions"
                    placeholder="选择"
                    :emptyTips="$t('system.noOption')"
                    :clear="false"
                    dataKey="label"
                    @change="handleRoleChange"
                  ></zxz-uni-data-select>
                </view>
              </view>
              <view class="rcc-item">
                <view class="rcc-label">份量：</view>
                <view class="uss-form-select">
                  <zxz-uni-data-select
                    v-model="formData.cookCount"
                    :localdata="recipeWeightOptions"
                    placeholder="选择"
                    :emptyTips="$t('system.noOption')"
                    :clear="false"
                    dataKey="label"
                    @change="handleRoleChange"
                  ></zxz-uni-data-select>
                </view>
              </view>
            </view>
            <view class="rcc-items">
              <view class="rcc-item rcc-item2">
                <view class="rcc-label">食材：</view>
                <view class="uss-form-view" @click="handleViewIngredient">
                  <view class="rcc-value">查看</view>
                  <ForwardIcons :size="iconSize2" color="#666" />
                </view>
              </view>
              <view class="rcc-item rcc-item2">
                <view class="rcc-label">调料：</view>
                <view class="uss-form-view" @click="handleViewSeason">
                  <view class="rcc-value">查看</view>
                  <ForwardIcons :size="iconSize2" color="#666" />
                </view>
              </view>
              <view class="rcc-item rcc-item2">
                <view class="rcc-label rcc-label2">
                  {{
                    g_options.getOptionText(
                      g_options.recipeTypeOptions,
                      formData.type,
                      '--'
                    )
                  }}菜谱
                </view>
              </view>
            </view>
            <!-- <view class="rcc-items">
              <view class="rcc-item rcc-item2">
                <view class="rcc-label">适用国家：</view>
                <view class="uss-form-select uss-form-select_country">
                  <zxz-uni-data-select
                    v-model="formData.tasteStyle"
                    :localdata="countryList"
                    placeholder="选择"
                    :emptyTips="$t('system.noOption')"
                    :clear="false"
                    dataKey="label"
                    @change="handleRoleChange"
                  ></zxz-uni-data-select>
                </view>
              </view>
              <view class="rcc-item rcc-item2">
                <view class="rcc-label">适用设备型号：</view>
                <view class="uss-form-select">
                  <zxz-uni-data-select
                    v-model="formData.tasteStyle"
                    :localdata="deviceModelList"
                    placeholder="选择"
                    :emptyTips="$t('system.noOption')"
                    :clear="false"
                    dataKey="label"
                    @change="handleRoleChange"
                  ></zxz-uni-data-select>
                </view>
              </view>
            </view> -->
          </view>
        </view>
      </view>
      <view class="recipe-box">
        <view class="recipe-content">
          <view class="recipe-step">
            <view class="rc-top">
              <view class="rct-left">详细步骤</view>
              <view class="rct-right">
                <nw-Button
                  :class="{
                    active: stepIndex > 0
                  }"
                  :disabled="!(stepIndex > 0)"
                  icon="arrow-upward"
                  text="上移一步"
                  @click="handleMoveUp"
                ></nw-Button>
                <nw-Button
                  :class="{
                    active:
                      stepIndex !== '' && stepIndex < recipeStepList.length - 1
                  }"
                  :disabled="
                    !(stepIndex !== '' && stepIndex < recipeStepList.length - 1)
                  "
                  icon="arrow-downward"
                  text="下移一步"
                  @click="handleMoveDown"
                ></nw-Button>
                <nw-Button
                  class="active"
                  icon="plus"
                  text="添加步骤"
                  @click="handleAddStep"
                ></nw-Button>
              </view>
            </view>
            <view class="rc-items">
              <up-radio-group
                v-if="recipeStepList.length"
                class="nw-radio-group"
                v-model="stepIndex"
              >
                <view
                  class="item"
                  v-for="(row, i) in recipeStepList"
                  :key="row"
                >
                  <nw-Radio :name="i" @change="handleRadioChange(row, i)">
                    <template #label>
                      <view class="item-left">
                        <view class="index">{{ i + 1 }}</view>
                        <view class="label">{{ row.name }}</view>
                      </view>
                      <view
                        class="label-radio"
                        :style="{
                          'z-index': stepIndex === i ? 10 : -1
                        }"
                        @click="handleRadioClick"
                      ></view>
                    </template>
                  </nw-Radio>
                  <view class="item-right">
                    <nw-Button
                      text="修改"
                      @click="handleEditStep(row, i)"
                    ></nw-Button>
                  </view>
                </view>
              </up-radio-group>
            </view>
            <view v-if="recipeStepList.length" class="rc-btns">
              <nw-Button
                text="保存"
                :disabled="formData.type === 0"
                @click.capture="handleSaveRecipe"
              ></nw-Button>
              <nw-Button
                text="生产新菜谱"
                @click="handleAddNewRecipe"
              ></nw-Button>
            </view>
            <view v-if="!recipeStepList.length" class="empty-list">
              当前为空菜谱
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
    <up-toast ref="uToastRef" />

    <!-- 刪除菜谱 -->
    <DeleteRecipe
      v-if="deleteRecipeVisible"
      v-model="deleteRecipeVisible"
      :row="formData"
      @confirm="handleDeleteRecipe"
    />
    <!-- 烹饪弹框 -->
    <SelectDevice
      v-if="selectDeviceVisible"
      v-model="selectDeviceVisible"
      :row="recipeRow"
      @confirm="handleAction"
    />
    <!-- 烹饪准备提示框 -->
    <PrepareRecipeTip
      v-if="prepareRecipeTipVisible"
      v-model="prepareRecipeTipVisible"
      @confirm="handleAction"
    />
    <!-- 食材详情 -->
    <IngredientDetail
      v-if="ingredientDetailVisible"
      v-model="ingredientDetailVisible"
      :row="formData"
      :stepList="recipeStepList"
    />
    <!-- 调料详情 -->
    <SeasonDetail
      v-if="seasonDetailVisible"
      v-model="seasonDetailVisible"
      :row="formData"
      :stepList="recipeStepList"
    />
    <!-- 添加与修改步骤弹框 -->
    <AddOrEditStep
      v-if="addOrEditStepVisible"
      v-model="addOrEditStepVisible"
      :type="addOrEditStepType"
      :row="stepRow"
      :boxIndex="boxIndex"
      :stepList="recipeStepList"
      @confirm="handleStepConfirm"
      @update="handleStepUpdate"
      @delete="handleStepDelete"
    />
  </nw-PageContainer>
</template>

<script setup>
import DeleteRecipe from './component/DeleteRecipe.vue'
import PrepareRecipeTip from './component/PrepareRecipeTip.vue'
import SelectDevice from './component/SelectDevice.vue'
import AddOrEditStep from './component/AddOrEditStep.vue'
import IngredientDetail from './component/IngredientDetail.vue'
import SeasonDetail from './component/SeasonDetail.vue'

const props = defineProps({
  type: {
    type: String,
    default: 'edit', // add-新增菜谱 edit-编辑/查看 manual-手动
    validator: value => ['add', 'edit', 'manual'].includes(value)
  },
  recipeType: {
    type: [String, Number],
    default: '0', // 0-菜谱库 1-调制中 2-收藏
    validator: value => ['0', '1', '2'].includes(String(value))
  },
  id: {
    type: String,
    default: ''
  }
})

const iconSize = ref(g_utils.rpxToPx(32))
const iconSize2 = ref(g_utils.rpxToPx(18))
const { bindDeviceList } = storeToRefs(useDeviceStore())
const recipeStore = useRecipeStore()
const {
  recipeLibraryList,
  recipeFormulatingList,
  recipeTempData,
  // 列表参数
  recipeTasteOptions,
  recipeCookStyleOptions,
  recipeWeightOptions
} = storeToRefs(recipeStore)
const { userInfo } = storeToRefs(useUserStore())
let recipeIndex = -1
// 数据源映射
const RECIPE_LISTS = computed(_ => {
  return {
    add: recipeFormulatingList.value,
    0: recipeLibraryList.value,
    1: recipeFormulatingList.value,
    2: recipeLibraryList.value
  }
})
// 定义操作映射表（类型 -> 对应的列表和跳转参数）
const ACTION_MAP = {
  // 添加操作
  add: data => RECIPE_LISTS.value.add.push(data),
  // 删除操作
  delete: () => RECIPE_LISTS.value[props.recipeType].splice(recipeIndex, 1),
  // 更新操作
  update: data =>
    RECIPE_LISTS.value[props.recipeType].splice(recipeIndex, 1, data)
}
const formData = ref({
  id: '',
  picturePath: '',
  name: '',
  tasteStyle: '',
  cookStyle: '',
  model: '',
  country: '',
  cookCount: '',
  stepList: [],
  status: 1,
  type: 1, // 菜谱类型：0-公共、1-私有、2-调制中
  createTime: '',
  updateTime: '',
  collect: 0
})
const stepIndex = ref('')
const recipeStepList = ref([])
const editIndex = ref('')
// 弹框参数
const uToastRef = ref(null)
const deleteRecipeVisible = ref(false)
const selectDeviceVisible = ref(false)
const recipeRow = ref({})
const prepareRecipeTipVisible = ref(false)
const ingredientDetailVisible = ref(false)
const seasonDetailVisible = ref(false)
const addOrEditStepVisible = ref(false)
const stepRow = ref({})
const addOrEditStepType = ref('add')
const boxIndex = ref('')

onMounted(_ => {
  getFormData()
  getDictDropList()
})

const getFormData = _ => {
  if (props.type === 'add') {
    // 设备型号为已绑定的设备型号
    formData.value.model = bindDeviceList.value
      .map(item => item.model)
      .join(',')
  } else if (props.type === 'edit' && props.id) {
    // 根据菜谱id获取对应的菜谱详情
    const foundItem = RECIPE_LISTS.value[props.recipeType].find((item, i) => {
      recipeIndex = i
      return item.id === props.id
    })
    if (foundItem) {
      g_utils.assignFormData(formData.value, foundItem)
      recipeStepList.value = g_.cloneDeep(foundItem.stepList || [])
    }
    console.log('recipeStepList.value', recipeStepList.value)
    console.log('foundItem', foundItem, 'recipeIndex', recipeIndex)
  } else if (props.type === 'manual') {
    formData.value = g_.cloneDeep(recipeTempData.value)
    recipeStepList.value = formData.value.stepList || []
  }
  console.log('formData.value', formData.value)
}

const getDictDropList = _ => {
  recipeStore.setRecipeTasteOptions()
  recipeStore.setRecipeCookStyleOptions()
  recipeStore.setRecipeWeightOptions()
}

const handleDelete = _ => {
  console.log('handleDelete')
  deleteRecipeVisible.value = true
}

const handleModifyPicture = _ => {
  console.log('handleModifyPicture', _)
  uni.chooseImage({
    count: 1, // 默认9
    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album'], // 从相册选择
    success: res => {
      // console.log('uni.chooseImage', res)
      g_utils.tempfileToBase64(res.tempFilePaths[0]).then(base64 => {
        // console.log('base64', base64)
        formData.value.picturePath = base64
        formData.value.base64Image = base64
      })
    }
  })
}

const handleCookImmedi = _ => {
  console.log('handleCookImmedi', _)
  selectDeviceVisible.value = true
  recipeRow.value = formData.value
}

const handleRoleChange = _ => {
  console.log('handleRoleChange:', _)
}

const handleViewIngredient = _ => {
  console.log('handleViewIngredient:', _)
  ingredientDetailVisible.value = true
}

const handleViewSeason = _ => {
  console.log('handleViewSeason:', _)
  seasonDetailVisible.value = true
}

const handleMoveUp = _ => {
  console.log('handleMoveUp', _)
  if (stepIndex.value < 1) return
  swapSteps(stepIndex.value, stepIndex.value - 1)
  stepIndex.value--
}

const handleMoveDown = _ => {
  console.log('handleMoveDown', stepIndex.value)
  if (
    stepIndex.value === '' ||
    stepIndex.value >= recipeStepList.value.length - 1
  )
    return
  swapSteps(stepIndex.value, stepIndex.value + 1)
  stepIndex.value++
}

const swapSteps = (index1, index2) => {
  const newList = [...recipeStepList.value]
  ;[newList[index1], newList[index2]] = [newList[index2], newList[index1]]
  recipeStepList.value = JSON.parse(JSON.stringify(newList))
}

const handleAddStep = _ => {
  console.log('handleAddStep', stepIndex.value)
  boxIndex.value =
    recipeStepList.value.filter(item => item.ingredientType === 'material')
      .length + 1
  addOrEditStepType.value = 'add'
  addOrEditStepVisible.value = true
}

const handleRadioChange = (row, i) => {
  console.log('handleRadioChange', row, i)
  stepIndex.value = i
}

const handleRadioClick = _ => {
  console.log('handleRadioClick')
  setTimeout(() => {
    stepIndex.value = ''
  })
}

const handleEditStep = (row, i) => {
  console.log('handleEditStep', row, i)
  boxIndex.value = recipeStepList.value
    .slice(0, i + 1)
    .filter(item => item.ingredientType === 'material').length
  addOrEditStepType.value = 'edit'
  stepRow.value = row
  editIndex.value = i
  addOrEditStepVisible.value = true
}

// 辅助函数：显示错误提示
const showToast = (message, type = 'error') => {
  uToastRef.value.show({ type, message })
}

const verifyRecipeSave = type => {
  const tipMap = {
    name: '菜谱名称不能为空',
    tasteStyle: '菜谱口味不能为空',
    cookStyle: '菜谱菜系不能为空',
    cookCount: '菜谱份量不能为空'
  }

  // 提取名称重复检查逻辑
  const checkDuplicateName = _ => {
    const recipeList = [
      ...recipeLibraryList.value,
      ...recipeFormulatingList.value
    ]
    const { id, name } = formData.value
    // 编辑模式：检查与其他菜谱重名
    if (type === 1) {
      return recipeList.find(item => item.id !== id && item.name === name)
    }
    // 新增模式
    if (props.recipeType * 1 === 1) {
      // 如果是"调制中"（recipeType=1），允许与自身重名，但不可与其他菜谱重名
      return recipeList.find(item => item.id !== id && item.name === name)
    } else {
      // 否则不允许与任何菜谱重名
      return recipeList.find(item => item.name === name)
    }
  }

  for (const key in tipMap) {
    if (!formData.value[key]) {
      showToast(tipMap[key])
      return false
    }
  }

  console.log('checkDuplicateName()', checkDuplicateName())
  if (checkDuplicateName()) {
    showToast('菜谱名称重复，请重新输入')
    return false
  }
  if (type === 2 && !recipeStepList.value.length) {
    showToast('菜谱中至少添加一个步骤')
    return false
  }
  // 检查食材盒是否补充完善
  for (const [i, step] of recipeStepList.value.entries()) {
    if (
      step.ingredientType === 'material' &&
      (!step.goal || !step.ingredientName)
    ) {
      showToast(`请完善步骤${i + 1}的食材信息`)
      return false
    }
  }
  // 表单部分字段数据修改
  // const { data } = await g_api.user.apiGetSystemTime()
  // 如果无菜谱创建时间，则创建-创建时间
  !formData.value.createTime && (formData.value.createTime = Date.now())
  formData.value.updateTime = Date.now()
  // 菜谱类型：0-公共、1-私有、2-调制中
  !formData.value.type && (formData.value.type = 1)

  return true
}

const handleSaveRecipe = _ => {
  console.log('handleSaveRecipe')
  if (formData.value.type * 1 === 0) {
    showToast('公共菜谱无法修改！', 'warning')
    return
  }
  if (verifyRecipeSave(1)) {
    // 如果是菜谱库列表中的菜谱，需要更新菜谱库列表，否则添加或更新到调制中
    const operation = ACTION_MAP[props.type === 'add' ? 'add' : 'update']
    const tabIndex = props.type === 'add' ? 1 : (props.recipeType ?? 0)
    // 如果无菜谱id，则创建id
    !formData.value.id && (formData.value.id = g_busTool.getRecipeId())

    // 保存为调制中的菜谱
    if (tabIndex * 1 === 1) {
      // 使用对象解构和默认值赋值
      formData.value = {
        ...formData.value,
        userId: formData.value.userId || userInfo.value.userId,
        nickName: formData.value.nickName || userInfo.value.nickName,
        type: 2
      }
    }
    console.log('formData.value', formData.value)

    // 执行列表更新操作
    operation({
      ...formData.value,
      stepList: recipeStepList.value
    })
    uni.reLaunch({
      url: `/pages/recipe/index?tabIndex=${tabIndex}`
    })
  }
}

const handleAddNewRecipe = _ => {
  console.log('handleAddNewRecipe')
  if (verifyRecipeSave(2)) {
    // 添加新菜谱到菜谱库列表，如果是调制中的菜谱，需要删除调制的菜谱
    const newFormData = {
      ...formData.value,
      stepList: recipeStepList.value
    }
    // 删除调制中的菜谱
    if (props.recipeType === '1') {
      recipeFormulatingList.value = recipeFormulatingList.value.filter(
        item => item.id !== formData.value.id
      )
    } else {
      newFormData.id = g_busTool.getRecipeId()
    }
    recipeLibraryList.value.push(newFormData)
    console.log('newFormData.value', newFormData.value)

    uni.reLaunch({
      url: `/pages/recipe/index?tabIndex=0`
    })
  }
}

const handleActionSelectChange = e => {
  console.log('handleActionSelectChange', e)
  // const { columnIndex, value, values, index, indexs } = e
}

const handleActionSelectConfirm = e => {
  console.log('handleActionSelectConfirm', e)
  // const data = e.value.filter(i => i)
  // const checkedNode = data[data.length - 1]
}

const handleDeleteRecipe = _ => {
  ACTION_MAP.delete() // 执行列表更新操作
  showToast(`该菜谱【${formData.value.name}】删除成功`, 'success')
  setTimeout(() => {
    deleteRecipeVisible.value = false
    uni.reLaunch({
      url: `/pages/recipe/index?tabIndex=${props.recipeType}`
    })
  }, 500)
}

const handleAction = data => {
  console.log('handleAction', data)
}

const handleStepConfirm = data => {
  console.log('handleStepConfirm', data)
  if (stepIndex.value + '') {
    recipeStepList.value.splice(stepIndex.value + 1, 0, data)
  } else {
    recipeStepList.value.push(data)
  }
}

const handleStepUpdate = data => {
  console.log('handleStepUpdate', data)
  recipeStepList.value.splice(editIndex.value, 1, data)
}

const handleStepDelete = data => {
  console.log('handleStepDelete', data, editIndex.value)
  if (stepIndex.value === editIndex.value) stepIndex.value = ''
  recipeStepList.value.splice(editIndex.value, 1)
  uToastRef.value.show({
    type: 'success',
    message: `该菜谱步骤【${data.name}】删除成功`
  })
}
</script>

<style lang="scss" scoped>
@import './scss/detail.scss';
</style>
